<template>
  <div class="roles-container">
    <div class="page-header">
      <h2>角色管理</h2>
      <el-button type="primary" @click="handleAdd">添加角色</el-button>
    </div>
    
    <el-table :data="roles" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="角色名称" width="150" />
      <el-table-column prop="code" label="角色代码" width="150" />
      <el-table-column prop="description" label="描述" />
      <el-table-column label="权限" width="300">
        <template #default="scope">
          <el-tag 
            v-for="permission in scope.row.permissions" 
            :key="permission"
            style="margin-right: 5px; margin-bottom: 5px"
          >
            {{ getPermissionName(permission) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(scope.row)"
            :disabled="scope.row.code === 'admin' || scope.row.code === 'teacher' || scope.row.code === 'student'"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑角色' : '添加角色'"
      width="600px"
    >
      <el-form :model="roleForm" :rules="rules" ref="roleFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色代码" prop="code">
          <el-input v-model="roleForm.code" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" rows="3" />
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <el-checkbox-group v-model="roleForm.permissions">
            <el-checkbox label="home">首页访问</el-checkbox>
            <el-checkbox label="students">学生管理</el-checkbox>
            <el-checkbox label="courses">课程管理</el-checkbox>
            <el-checkbox label="grades">成绩管理</el-checkbox>
            <el-checkbox label="users">用户管理</el-checkbox>
            <el-checkbox label="roles">角色管理</el-checkbox>
            <el-checkbox label="course-selection">选课管理</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 权限映射表
const permissionMap = {
  'home': '首页访问',
  'students': '学生管理',
  'courses': '课程管理',
  'grades': '成绩管理',
  'users': '用户管理',
  'roles': '角色管理',
  'course-selection': '选课管理'
};

// 模拟角色数据
const mockRoles = [
  {
    id: 1,
    name: '管理员',
    code: 'admin',
    description: '系统管理员，拥有所有权限',
    permissions: ['home', 'students', 'courses', 'grades', 'users', 'roles']
  },
  {
    id: 2,
    name: '教师',
    code: 'teacher',
    description: '教师用户，可以管理学生、课程和成绩',
    permissions: ['home', 'students', 'courses', 'grades']
  },
  {
    id: 3,
    name: '学生',
    code: 'student',
    description: '学生用户，可以查看课程、成绩和进行选课',
    permissions: ['home', 'courses', 'grades', 'course-selection']
  }
];

// 状态变量
const roles = ref([...mockRoles]);
const loading = ref(false);
const dialogVisible = ref(false);
const isEdit = ref(false);
const roleFormRef = ref(null);

// 角色表单
const roleForm = reactive({
  id: 0,
  name: '',
  code: '',
  description: '',
  permissions: []
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色代码', trigger: 'blur' },
    { pattern: /^[a-z0-9-]+$/, message: '角色代码只能包含小写字母、数字和连字符', trigger: 'blur' }
  ],
  permissions: [
    { type: 'array', required: true, message: '请至少选择一个权限', trigger: 'change' }
  ]
};

// 生命周期钩子
onMounted(() => {
  // 模拟加载数据
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 500);
});

// 方法
const getPermissionName = (code) => {
  return permissionMap[code] || code;
};

const resetForm = () => {
  roleForm.id = 0;
  roleForm.name = '';
  roleForm.code = '';
  roleForm.description = '';
  roleForm.permissions = [];
  if (roleFormRef.value) {
    roleFormRef.value.resetFields();
  }
};

const handleAdd = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  isEdit.value = true;
  Object.assign(roleForm, row);
  dialogVisible.value = true;
};

const handleDelete = (row) => {
  if (['admin', 'teacher', 'student'].includes(row.code)) {
    ElMessage.warning('不能删除系统预设角色');
    return;
  }
  
  ElMessageBox.confirm(
    `确定要删除角色 ${row.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 模拟删除操作
      const index = roles.value.findIndex(role => role.id === row.id);
      if (index !== -1) {
        roles.value.splice(index, 1);
        ElMessage.success('删除成功');
      }
    })
    .catch(() => {
      // 取消删除
    });
};

const submitForm = () => {
  if (!roleFormRef.value) return;
  
  roleFormRef.value.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        // 编辑角色
        const index = roles.value.findIndex(role => role.id === roleForm.id);
        if (index !== -1) {
          roles.value[index] = { ...roleForm };
          ElMessage.success('更新成功');
        }
      } else {
        // 添加角色
        // 检查角色代码是否已存在
        const exists = roles.value.some(role => role.code === roleForm.code);
        if (exists) {
          ElMessage.error('角色代码已存在');
          return;
        }
        
        // 生成新ID
        const newId = Math.max(...roles.value.map(role => role.id)) + 1;
        const newRole = { ...roleForm, id: newId };
        roles.value.push(newRole);
        ElMessage.success('添加成功');
      }
      
      dialogVisible.value = false;
    }
  });
};
</script>

<style scoped>
.roles-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>